package cn.mes.controller;

import cn.mes.entity.FormData;
import cn.mes.service.impl.IMesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class MesController {
    private Logger log = LoggerFactory.getLogger(MesController.class);
    @Autowired
    private IMesService mesService;

    /**
     * 留言列表
     *
     * @return
     */
    @GetMapping(value = "/mesList")
    public List<Map<String, Object>> mesList() {
        List<Map<String, Object>> maps = mesService.mesList();
        return maps;
    }

    /**
     * 新增留言
     *
     * @param formData
     * @return
     */
    @PostMapping(value = "/submitForm")
    public String submitForm(@RequestBody FormData formData, HttpServletRequest request) {
        if (formData.getMessage().isEmpty()) {
            return "留言不能为空";
        }
        String ip = request.getRemoteAddr();
        System.out.println("姓名：" + formData.getName() +
                " 邮箱：" + formData.getEmail() +
                " 留言：" + formData.getMessage());
        log.info("姓名:{},邮箱:{},留言:{},ip:{}", formData.getName(), formData.getEmail(), formData.getMessage(), ip);
        formData.setCreateTime(new Date());
        formData.setIp(ip);
        int result = mesService.submitForm(formData);
        if (result > 0) {
            return "数据已成功提交：" + formData.getName();
        } else {
            return "数据提交失败";
        }
    }

    /**
     * /**
     * 修改留言
     *
     * @param formData
     * @return
     */
    @PostMapping(value = "/update")
    public String updateMessage(@RequestBody FormData formData) {
        if (formData.getMessage().isEmpty()) {
            return "留言不能为空";
        }
        mesService.updateMessage(formData);
        return "留言修改成功";
    }

    /**
     * 删除留言
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/delete")
    public String deleteMessage(String id) {
        mesService.deleteMessage(id);
        return "留言删除成功";
    }

}
